package br.trainee.web.filtros;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.trainee.web.util.UtilFuncoes;

//@WebFilter(urlPatterns=("/paginas/*"))
public class FiltroLogin implements Filter{

	@Override
	public void destroy() {
		
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpServletRequest request = (HttpServletRequest) req;
		
		HttpSession sessao = request.getSession();
		
		if(sessao.getAttribute(UtilFuncoes.USUARIO_SESSAO) != null){
			
			chain.doFilter(request, response);
		}
		else{
			
			//Aqui é aberta uma nova requisição GET. Neste pont a última requisição é esquecida
			response.sendRedirect(request.getContextPath() + "/login.jsp");
			
			//RequestDispatcher rec = request.getRequestDispatcher("/login.jsp");
			//rec.forward(request, response);
		}
		
		
	}
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
		
	}

}
